package com.gonghui.videomanage;

import android.animation.Animator;
import android.content.Intent;
import android.graphics.SurfaceTexture;
import android.media.MediaPlayer;
import android.util.Log;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewPropertyAnimator;
import android.view.WindowInsets;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import java.io.IOException;

/**
 * Created by gonghui on 2016/10/8.
 */

public class VideoManage implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnSeekCompleteListener, TextureView.SurfaceTextureListener, View.OnClickListener, Animator.AnimatorListener, SeekBar.OnSeekBarChangeListener {
    private static VideoManage videoManage = new VideoManage();
    private MediaPlayer mediaPlayer;
    private String path;
    private ViewGroup viewGroup;
    private View view;
    private TextureView textureView;
    private ProgressBar progressBar;
    private ImageView iv_btn_play, iv_btn_screen;
    private SeekBar sb_progress;
    private TextView tv_cur_time, tv_all_time;
    private RelativeLayout rl_media_layout;
    private LinearLayout ll_play_ctrl;
    private ViewPropertyAnimator animate;
    private Surface surface;

    private VideoManage() {
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnPreparedListener(this);
        mediaPlayer.setOnCompletionListener(this);
        mediaPlayer.setOnBufferingUpdateListener(this);
        mediaPlayer.setOnSeekCompleteListener(this);
    }

    public static VideoManage getInstance() {
        return videoManage;
    }

    public VideoManage setRoot(ViewGroup viewGroup) {
        reset();
        this.viewGroup = viewGroup;

        view = View.inflate(viewGroup.getContext(), R.layout.video_layout, viewGroup);
        textureView = (TextureView) view.findViewById(R.id.textureView);
        textureView.setSurfaceTextureListener(this);
        progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
        rl_media_layout = (RelativeLayout) view.findViewById(R.id.rl_media_layout);
        rl_media_layout.setOnClickListener(this);
        ll_play_ctrl = (LinearLayout) view.findViewById(R.id.ll_play_ctrl);
        animate = ll_play_ctrl.animate();
        animate.setListener(this);
        iv_btn_play = (ImageView) view.findViewById(R.id.iv_btn_play);
        iv_btn_play.setOnClickListener(this);
        tv_cur_time = (TextView) view.findViewById(R.id.tv_cur_time);
        sb_progress = (SeekBar) view.findViewById(R.id.sb_progress);
        sb_progress.setOnSeekBarChangeListener(this);
        tv_all_time = (TextView) view.findViewById(R.id.tv_all_time);
        iv_btn_screen = (ImageView) view.findViewById(R.id.iv_btn_screen);
        iv_btn_screen.setOnClickListener(this);
        return this;
    }

    public VideoManage setPath(String path) {
        this.path = path;
        return this;
    }

    public void prepare() {
        try {
            mediaPlayer.setDataSource(path);
            mediaPlayer.prepareAsync();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start(){
        WakeLockUtil.getInstance(viewGroup.getContext()).open();
        mediaPlayer.start();
        iv_btn_play.setImageResource(R.mipmap.pause);
    }

    public void pause(){
        WakeLockUtil.getInstance(viewGroup.getContext()).close();
        mediaPlayer.pause();
        iv_btn_play.setImageResource(R.mipmap.start);
    }

    public void stop() {
        WakeLockUtil.getInstance(viewGroup.getContext()).close();
        mediaPlayer.stop();
        mediaPlayer.reset();
    }

    public void reset() {
        if (viewGroup != null && viewGroup.getChildCount() > 0) {
            viewGroup.removeAllViews();
            viewGroup.setVisibility(View.GONE);
        }
    }

    public void release() {
        mediaPlayer.stop();
        mediaPlayer.reset();
        mediaPlayer.release();
    }

    @Override
    public void onPrepared(MediaPlayer mediaPlayer) {
        Log.i("qwe", "onPrepared: ");
        sb_progress.setMax(mediaPlayer.getDuration());
        tv_all_time.setText(formatTime(mediaPlayer.getDuration() / 1000));
        iv_btn_play.setImageResource(R.mipmap.pause);
        progressBar.setVisibility(View.GONE);
        start();
    }

    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        Log.i("qwe", "onCompletion: ");
        WakeLockUtil.getInstance(viewGroup.getContext()).close();
    }

    @Override
    public void onBufferingUpdate(MediaPlayer mediaPlayer, int percent) {
        sb_progress.setSecondaryProgress(mediaPlayer.getDuration() * percent / 100);
    }

    @Override
    public void onSeekComplete(MediaPlayer mediaPlayer) {

    }

    @Override
    public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int i, int i1) {
        Log.i("qwe", "onSurfaceTextureAvailable: ");
        surface = new Surface(surfaceTexture);
        mediaPlayer.setSurface(surface);
    }

    @Override
    public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int i, int i1) {

    }

    @Override
    public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
        Log.i("qwe", "onSurfaceTextureDestroyed: ");
        stop();
        return false;
    }

    @Override
    public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {
        sb_progress.setProgress(mediaPlayer.getCurrentPosition());
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.iv_btn_play) {
            if (mediaPlayer.isPlaying()) {
                pause();
            } else {
                start();
            }
        }
        if (view.getId() == R.id.iv_btn_screen) {
            Intent intent = new Intent(viewGroup.getContext(), FullScreenActivity.class);
            viewGroup.getContext().startActivity(intent);
        }
    }

    @Override
    public void onAnimationStart(Animator animator) {

    }

    @Override
    public void onAnimationEnd(Animator animator) {

    }

    @Override
    public void onAnimationCancel(Animator animator) {

    }

    @Override
    public void onAnimationRepeat(Animator animator) {

    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if (fromUser)
            mediaPlayer.seekTo(progress);

        tv_cur_time.setText(formatTime(progress / 1000));
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }

    public void onFullScreenResult() {
        mediaPlayer.setSurface(surface);
    }

    public MediaPlayer getMediaPlayer() {
        return mediaPlayer;
    }

    private OnVideoScrollListener mOnVideoScrollListener = new OnVideoScrollListener();
    private class OnVideoScrollListener implements AbsListView.OnScrollListener{

        @Override
        public void onScrollStateChanged(AbsListView absListView, int state) {
            onVideoScrolling(state);
        }

        @Override
        public void onScroll(AbsListView absListView, int i, int i1, int i2) {

        }
    }

    public OnVideoScrollListener getOnVideoScrollListener() {
        return mOnVideoScrollListener;
    }

    public void onVideoScrolling(int state){
        if (viewGroup != null) {
            int[] location = new int[2];
            viewGroup.getLocationOnScreen(location);
            Log.i("qwe", "view y: " + location[1]);
            Log.i("qwe", "getChildCount: " + viewGroup.getChildCount());
            if (state == AbsListView.OnScrollListener.SCROLL_STATE_IDLE && (location[1] < 0 || location[1] > viewGroup.getResources().getDisplayMetrics().heightPixels || viewGroup.getChildCount() == 0)) {
                Log.i("qwe", "viewGroup: GONE");
                viewGroup.removeAllViews();
                viewGroup.setVisibility(View.GONE);
            }
        }
    }

    private String formatTime(int time) {
        String minute = time / 60 > 9 ? "" + time / 60 : "0" + time / 60;
        String second = time % 60 > 9 ? "" + time % 60 : "0" + time % 60;
        return minute + ":" + second;
    }
}
